//
//  WZOutManagerController.m
//  ETong
//
//  Created by wanzhao on 15/11/17.
//  Copyright (c) 2015年 wanzhao. All rights reserved.
//

#import "WZOutManagerController.h"
#import "WZOutCountController.h"
#import "WZOutCell.h"
#import "WZOutFrame.h"
#import "CFolderMgr.h"
#import "MJExtension.h"
#import "UIBarButtonItem+category.h"
#import "MBProgressHUD+WZ.h"
#import "NetWorkShare.h"
#import <BaiduMapAPI_Utils/BMKUtilsComponent.h>
#import <BaiduMapAPI_Location/BMKLocationService.h>
#import <BaiduMapAPI_Search/BMKGeocodeSearch.h>
#import <BaiduMapAPI_Search/BMKSearchComponent.h>
#import "WZOutDistance.h"
#import <CoreLocation/CoreLocation.h>
#import "WZLocationViewController.h"
#import "WZOutCoor.h"
#import "WZOutListController.h"

#define OutManger_TableID @"wcqdqtspd"
#define OutManger_LoadData @"无相关外出单"
#define OutManger_Location @"定位中..."
#define OutManger_Location_Service_Message @"您未打开定位服务!请前往:设置->隐私->定位服务中开启"

@interface WZOutManagerController ()<UITableViewDataSource, UITableViewDelegate,BMKLocationServiceDelegate, BMKGeoCodeSearchDelegate, UIAlertViewDelegate>

@property (nonatomic, strong) NSMutableArray *outDataArray;
@property (nonatomic, weak) UITableView *tableView;
@property (nonatomic, strong) CAccountModel *curAccount;
@property (nonatomic, weak) UITextField *addressText;
@property (nonatomic, weak) UIButton *signBtn;
@property (nonatomic, weak) UIButton *signOutBtn;
@property (nonatomic, copy) NSString *signFlag;
@property (nonatomic, strong) WZOut *wzout;
@property (nonatomic, copy) NSString *latitude;
@property (nonatomic, copy) NSString *longitude;
@property (nonatomic, copy) NSString *address;
@property (nonatomic, copy) NSDateFormatter *fm;
@property (nonatomic, assign) NSInteger selectedRowNum;


/**OA用户名*/
@property (nonatomic, copy) NSString *oaUserName;
/**OA 登陆密码*/
@property (nonatomic, copy) NSString *oaPwd;
/**OA userId*/
@property (nonatomic, copy) NSString *oaUserId;
/**OA 公司ID*/
@property (nonatomic, copy) NSString *oaCompanyID;
/**OA 姓名*/
@property (nonatomic, copy) NSString *oaName;

/**地理编码*/
@property (nonatomic, assign) BOOL isGeoCode;
/**发地理编码*/
@property (nonatomic, assign) BOOL isReGeoCode;
/**地理编码搜索*/
@property (nonatomic, strong) BMKGeoCodeSearch *geoCodeSearch;
@property (nonatomic, strong) BMKLocationService *locationService;
@property (nonatomic, strong) BMKUserLocation *location;
/**外出坐标*/
@property (nonatomic, assign) CLLocationCoordinate2D outCoordiNate2D;
/**用户坐标*/
@property (nonatomic, assign) CLLocationCoordinate2D userCoordiNate2D;

@property (nonatomic, assign) BOOL selectedFlag;
@property (nonatomic, assign) float distance;
@property (nonatomic, strong) NSMutableArray *distanceArray;
@property (nonatomic, strong) NSMutableArray *coordinateArray;
@property (nonatomic, strong) NSMutableArray *listArray;
@property (nonatomic, strong) NSMutableArray *outSignArray;
@property (nonatomic, copy) NSString *applyUrl;

@end

@implementation WZOutManagerController

- (void)dealloc
{
    _geoCodeSearch.delegate = nil;
    _locationService.delegate = nil;
    self.longitude = nil;
    self.latitude = nil;
    self.address = nil;
    
    WZLog(@"WZOutManagerController  dealloc");
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setupView];
    
    [self addChildControl];
    
    [self loadOutData];
    
    [self setupLocationService];
}

- (void)viewDidAppear:(BOOL)animated {
    
    [super viewDidAppear:animated];
    
    //    NSString *flag = [[NSUserDefaults standardUserDefaults] objectForKey:@"outSignFlag"];
    //
    //    if ([flag isEqualToString:@"1"]) {
    //
    //        [MBProgressHUD showError:@"有未签退的外出单哦~~~" toView:self.view];
    //    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (!IsIOS7) {
        self.navigationController.navigationBar.tintColor = RGBCOLORWITH16COLOR(0x3899e8);
    } else {
        self.navigationController.navigationBar.barTintColor = RGBCOLORWITH16COLOR(0x3899e8);
    }
    
    // 判断本应用是否允许定位
    CLAuthorizationStatus type = [CLLocationManager authorizationStatus];
    if (![CLLocationManager locationServicesEnabled] || type == kCLAuthorizationStatusDenied) {
        
        [MBProgressHUD hideAllHUDsForView:self.view animated:NO];
        [self setupAlertView];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
}


- (void)setupView {
    
    self.view.backgroundColor = RGBCOLORWITH16COLOR(0xf5f5f5);
    self.navigationItem.title = @"外出单";
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem BarButtonItemWithImageName:nil title:@"签到统计" target:self sel:@selector(signCount) titleFont:Font12 titleColor:WhiteColor];
    
    //    self.curAccount = [[CFolderMgr shareInstance].accMgr getRecentlyLoginAccount];
    self.fm = [[NSDateFormatter alloc] init];
    self.fm.timeZone = [NSTimeZone systemTimeZone];
    self.fm.locale =[NSLocale currentLocale];
    self.fm.dateFormat = @"yyyy-MM-dd HH:mm";
    
    // 获取OA账户信息
    self.oaUserName = [USER_DEFAULT objectForKey:@"oaUserName"];
    self.oaUserId = [USER_DEFAULT objectForKey:@"oaUserId"];
    self.oaPwd = [USER_DEFAULT objectForKey:@"oaPwd"];
    self.oaCompanyID = [USER_DEFAULT objectForKey:@"oaCompanyID"];
    self.oaName = [USER_DEFAULT objectForKey:@"oaName"];
    
}


- (void)setupLocationService {
    
    [MBProgressHUD showMessage:OutManger_Location toView:self.view];
    
    _locationService = [[BMKLocationService alloc] init];
    _locationService.delegate = self;
    [_locationService startUserLocationService];
    self.addressText.text = OutManger_Location;
    
    // 创建地理编码
    _geoCodeSearch = [[BMKGeoCodeSearch alloc] init];
    _geoCodeSearch.delegate = self;
}

#pragma mark -- 定位, 反地理编码
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation {
    
    _isReGeoCode = true;
    [MBProgressHUD hideHUDForView:self.view];
    self.userCoordiNate2D = userLocation.location.coordinate;
    [_locationService stopUserLocationService];
    self.latitude = [NSString stringWithFormat:@"%f",userLocation.location.coordinate.latitude];
    self.longitude = [NSString stringWithFormat:@"%f",userLocation.location.coordinate.longitude];
    
    // 创建反地理编码检索信息类
    BMKReverseGeoCodeOption *op = [[BMKReverseGeoCodeOption alloc] init];
    op.reverseGeoPoint = userLocation.location.coordinate;
    [_geoCodeSearch reverseGeoCode:op];
    
    if (_isReGeoCode) {
        WZLog(@"反地理编码成功!");
    } else {
        
        WZLog(@"反地理编码失败!");
    }
    
    WZLog(@"定位经纬度 = %@ - %@", self.latitude, self.longitude);
}

# pragma mark -- 地理编码
- (void)genCodeWithOutAddress:(NSString *)outAddress {
    
    _isGeoCode = false;
    BMKGeoCodeSearch *geo = [[BMKGeoCodeSearch alloc] init];
    geo.delegate = self;
    
    BMKGeoCodeSearchOption *geoCodeOption = [[BMKGeoCodeSearchOption alloc] init];
    //    geoCodeOption.city = @"北京";
    geoCodeOption.address = outAddress;
    [geo geoCode:geoCodeOption];
}

- (void)onGetGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error {
    
    WZLog(@"result = %@", result);
    if (error == BMK_SEARCH_NO_ERROR) {
        
        self.outCoordiNate2D = result.location;
        
        BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];
        item.coordinate = result.location;
        item.title = result.address;
        NSString* titleStr;
        NSString* showmeg;
        
        titleStr = @"正向地理编码";
        showmeg = [NSString stringWithFormat:@"纬度:%f,经度:%f",item.coordinate.latitude,item.coordinate.longitude];
        
        NSLog(@"地理编码后的经纬度 = %@", showmeg);
        
        UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:titleStr message:showmeg delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定",nil];
        [myAlertView show];
    }
}

- (void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error {
    
    //    WZLog(@"GeverseSearch Result = %@-%@-%f=%f-%@", result.addressDetail, result.address, result.location.longitude, result.location.latitude, result.poiList);
    //
    //    WZLog(@"%@＝%@＝%@＝%@＝%@＝%@＝%@",result.addressDetail.streetName,result.addressDetail.streetNumber,result.addressDetail.district,result.addressDetail.city,result.addressDetail.province,result.address,result.businessCircle);
    
    //    for (BMKPoiInfo *info in result.poiList) {
    //        WZLog(@"info = %@-%@-%@-%@", info.name, info.address, info.phone, info.city);
    //
    //    }
    
    if (error == BMK_SEARCH_NO_ERROR) {
        
        [MBProgressHUD hideHUDForView:self.view];
        self.address = result.address;
        self.addressText.text = [NSString stringWithFormat:@"当前地址：%@",self.address];
        WZLog(@"address = %@", self.addressText.text);
    }
}

#pragma mark -- 计算两个坐标间距离
- (float)distanceWithOutCoordinate2D:(CLLocationCoordinate2D)outCoordinate userCoordinate:(CLLocationCoordinate2D)userCoordinate {
    
    BMKMapPoint point1 = BMKMapPointForCoordinate(outCoordinate);
    BMKMapPoint point2 = BMKMapPointForCoordinate(userCoordinate);
    float distance = BMKMetersBetweenMapPoints(point1,point2);
    return distance;
}


#pragma mark - 加载外出单数据

- (void)loadOutData
{
    [MBProgressHUD showMessage:@"加载数据中..." toView:self.view];
    [NetWorkShare getOutListWithUserid:self.oaUserId successHandle:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        [MBProgressHUD hideHUDForView:self.view];
        
        if (responseObject) {
            
            if ([[responseObject objectForKey:@"success"] boolValue]) {
                
                [self.outDataArray removeAllObjects];
                NSArray *outArray = [WZOut objectArrayWithKeyValuesArray:responseObject[@"list"]];
                
                for (WZOut *wzout in outArray) {
                    
                    WZOutFrame *outFrame = [[WZOutFrame alloc] init];
                    outFrame.wzOut = wzout;
                    CLLocationCoordinate2D outCoordiNate2D = [self transformCoordinate2DWithPositionStr:wzout.position];
                    _distance = [self distanceWithOutCoordinate2D:outCoordiNate2D userCoordinate:_userCoordiNate2D];
                    wzout.distance = _distance;
                    
                    [self.outDataArray addObject:outFrame];
                    
                }
                
            } else {
                
                [MBProgressHUD showError:[responseObject objectForKey:@"message"]];
            }
            
        } else {
            [MBProgressHUD hideAllHUDsForView:self.view animated:NO];
            [MBProgressHUD showError:UNKNOWNERROR];
        }
        
        [self.tableView reloadData];
        
    } failureHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:NO];
        [MBProgressHUD showError:NETWORKNERROR toView:self.view];
        
    }];
    
}

#pragma mark - 签到数量

- (void)signCount
{
    WZOutCountController *outCount = [[WZOutCountController alloc] init];
    outCount.oaUserId =  self.oaUserId;
    [self.navigationController pushViewController:outCount animated:YES];
}


#pragma mark - 跳转定位控制器

- (void)showLocation
{
    if (self.latitude == nil || self.longitude == nil) {
        
        [MBProgressHUD showError:OutManger_Location toView:self.view];
        return;
        
    } else if (!self.outDataArray.count) {
        
        WZLocationViewController *loVC = [[WZLocationViewController alloc] init];
        loVC.userCoordiNate2D = self.userCoordiNate2D;
        [self.navigationController pushViewController:loVC animated:YES];
        
    } else {
        
        WZOutFrame *outFrame = self.outDataArray[self.selectedRowNum];
        
        if (!self.selectedFlag) { // don't selected List
            
            //            [MBProgressHUD showError:@"请选择客户名称" toView:self.view];
            //            return;
            
            WZLocationViewController *loVC = [[WZLocationViewController alloc] init];
            loVC.userCoordiNate2D = self.userCoordiNate2D;
            //            loVC.outCoordiNate2D = outFrame.wzOut.outCoordiNate2D;
            //            loVC.wzout = outFrame.wzOut;
            
            
            if (!self.address) {
                self.addressText.text = [NSString stringWithFormat:@"当前地址: %@", OutManger_Location];
            } else {
                
                self.addressText.text = [NSString stringWithFormat:@"当前地址: %@", self.address];
            }
            
            [self.navigationController pushViewController:loVC animated:YES];
            
        } else { // 选中外出单
            
            WZLocationViewController *loVC = [[WZLocationViewController alloc] init];
            loVC.userCoordiNate2D = self.userCoordiNate2D;
            CLLocationCoordinate2D outCoordinate2D = [self transformCoordinate2DWithPositionStr:outFrame.wzOut.position];
            loVC.outCoordiNate2D = outCoordinate2D;
            loVC.wzout = outFrame.wzOut;
            
            
            if (!self.address) {
                self.addressText.text = [NSString stringWithFormat:@"当前地址: %@", OutManger_Location];
            } else {
                
                self.addressText.text = [NSString stringWithFormat:@"当前地址: %@", self.address];
            }
            
            [self.navigationController pushViewController:loVC animated:YES];
        }
    }
}



- (void)btnClick:(UIButton *)btn
{
    if (self.latitude == nil || self.longitude == nil || self.address == nil) {
        [MBProgressHUD showError:OutManger_Location toView:self.tableView];
        return;
    }
    
    switch (btn.tag) {
            //上班签到
        case 20001:
        {
            self.signFlag = @"1";
            NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
            [userDefault setObject:_signFlag forKey:@"outSignFlag"];
        }
            break;
            //下班签退
        case 20002:
        {
            self.signFlag = @"2";
            NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
            [userDefault setObject:_signFlag forKey:@"outSignFlag"];
        }
            break;
            
        default:
            break;
    }
    [MBProgressHUD showMessage:@"请稍后..." toView:self.view];
    
    
    [NetWorkShare getWorkFlowWithApplyAndLoginName:self.oaUserName password:self.oaPwd companyId:self.oaCompanyID FormId:OutManger_TableID successHandle:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        if ([[responseObject objectForKey:@"success"] boolValue]) {
            
            [MBProgressHUD hideHUDForView:self.view];
            [self.listArray removeAllObjects];
            self.listArray = [WZOutProceduleList objectArrayWithKeyValuesArray:responseObject[@"datas"]];
            
            self.applyUrl = responseObject[@"applyUrl"];
            
            WZLog(@"count = %lu", (unsigned long)self.listArray.count);
            NSNumber *num = [NSNumber numberWithUnsignedInteger:self.listArray.count];
            [[NSNumber numberWithUnsignedInteger:self.listArray.count] isEqualToNumber:@(0)];
            WZLog(@"%@", num);
            
            if (!self.listArray.count) {
                
                // TODO: 没有流程
                [MBProgressHUD showError:@"没有外出流程"];
                
            } else {
                
                if (self.listArray.count > 1) {
                    
                    //                            self.tableView.hidden = NO;
                    [self.view setNeedsDisplay];
                    WZOutListController *applyVc = [[WZOutListController alloc] init];
                    applyVc.formId = OutManger_TableID;
                    applyVc.oaUserName = self.oaUserName;
                    applyVc.oaPwd = self.oaPwd;
                    applyVc.oaCompanyID = self.oaCompanyID;
                    applyVc.oaUserName = self.oaUserName;
                    applyVc.signFlag = self.signFlag;
                    applyVc.longitude = self.longitude;
                    applyVc.latitude = self.latitude;
                    applyVc.oaUserId = self.oaUserId;
                    applyVc.outId = self.wzout.outId;
                    applyVc.address = self.address;
                    applyVc.block = ^(BOOL isSuccess){
                        
                        [self updateUI];
                    };
                    
                    [self.navigationController pushViewController:applyVc animated:YES];
                    
                } else if (self.listArray.count == 1 && [[self.listArray.firstObject runState] isEqualToString:@"运行中"]) {
                    
                    // 直接打开
                    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
                    parameters[@"userId"] = self.oaUserId;
                    parameters[@"applyId"] = self.wzout.outId;
                    parameters[@"address"] = self.address;
                    parameters[@"typeFlag"] = self.signFlag;
                    parameters[@"longitude"] = self.longitude;
                    parameters[@"latitude"] = self.latitude;
                    WZOutProceduleList *outList = self.listArray.lastObject;
                    parameters[@"modelId"] = outList.modelId;
                    parameters[@"mversion"] = outList.mversion;
                    parameters[@"fversion"] = outList.fversion;
                    parameters[@"startEventkey"] = outList.startEventKey;
                    
                    [NetWorkShare outSignOrSignOutWithProcedureParameters:parameters successHandle:^(AFHTTPRequestOperation *operation, id responseObject) {
                        
                        if ([[responseObject objectForKey:@"success"] boolValue]) {
                            
                            if ([self.signFlag isEqualToString:@"1"]) {
                                self.wzout.signBeginTime = [NSDate getCurrentDateWithDateFormatterStr:@"YYYY-MM-dd HH:mm:ss"];
                                [MBProgressHUD showSuccess:@"签到成功"];
                                self.signBtn.enabled = NO;
                                self.signOutBtn.enabled = YES;
                                
                            } else {
                                
                                self.wzout.signEndTime = [NSDate getCurrentDateWithDateFormatterStr:@"YYYY-MM-dd HH:mm:ss"];
                                [MBProgressHUD showSuccess:@"签退成功"];
                                self.signOutBtn.enabled = NO;
                                self.signBtn.enabled = YES;
                            }
                        } else {
                            [MBProgressHUD hideHUDForView:self.view];
                            [MBProgressHUD showError:[responseObject objectForKey:@"message"]];
                        }
                        
                    } failureHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
                        [MBProgressHUD hideHUDForView:self.view];
                        [MBProgressHUD showError:NETWORKNERROR toView:self.view];
                    }];
                }
            }
            
        } else {
            
            [MBProgressHUD hideHUDForView:self.view];
            [MBProgressHUD showError:[responseObject objectForKey:@"message"] toView:self.view];
        }
        
    } failureHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [MBProgressHUD hideHUDForView:self.view];
        [MBProgressHUD showError:NETWORKNERROR toView:self.view];
    }];
    
    /*************** 正常逻辑 未走工作流 *************
     
     [NetWorkShare outSignOrSignOutWithUserId:self.oaUserId applyid:self.wzout.outId typeFlag:self.signFlag address:self.address longitude:self.longitude latitude:self.latitude successHandle:^(AFHTTPRequestOperation *operation, id responseObject) {
     [MBProgressHUD hideHUDForView:self.view];
     if (responseObject) {
     
     if ([[responseObject objectForKey:@"success"] boolValue]) {
     
     if ([self.signFlag isEqualToString:@"1"]) {
     self.wzout.signBeginTime = [NSDate getCurrentDateWithDateFormatterStr:@"YYYY-MM-dd HH:mm:ss"];
     [MBProgressHUD showSuccess:@"签到成功"];
     self.signBtn.enabled = NO;
     self.signOutBtn.enabled = YES;
     
     } else {
     
     self.wzout.signEndTime = [NSDate getCurrentDateWithDateFormatterStr:@"YYYY-MM-dd HH:mm:ss"];
     [MBProgressHUD showSuccess:@"签退成功"];
     self.signOutBtn.enabled = NO;
     self.signBtn.enabled = YES;
     }
     } else {
     [MBProgressHUD showError:[responseObject objectForKey:@"message"]];
     }
     
     } else {
     [MBProgressHUD showError:@"未知错误"];
     }
     
     } failureHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
     
     [MBProgressHUD showError:NETWORKNERROR toView:self.view];
     }];
     
     *************** END *************/
    
}



#pragma mark tableView相关方法

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.outDataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WZOutFrame *outFrame = self.outDataArray[indexPath.row];
    return outFrame.cellHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return OppositeHeightRate(10);
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return OppositeHeightRate(10);
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = ClearColor;
    return view;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = ClearColor;
    return view;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WZOutCell *cell = [WZOutCell outCellWithTableView:tableView];
    WZOutFrame *outFrame = self.outDataArray[indexPath.row];
    cell.outFrame = outFrame;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.selectedRowNum = tableView.indexPathForSelectedRow.row;
    
    if ([self.signFlag isEqualToString:@"1"]) {
        self.signFlag = @"1";
        [MBProgressHUD showError:@"您有未签退的外出单" toView:self.view];
        return;
    } else if ([self.signFlag isEqualToString:@"2"]) {
        
        
    } else { // signFlag == nil
        
        WZLog(@"self.signFlag == nil");
    }
    
    
    //    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    //    NSString *strFlag = [userDefault objectForKey:@"outSignFlage"];
    //
    //    if ([strFlag isEqualToString:@"1"]) {
    //
    //        [MBProgressHUD showError:@"您有未签退的外出单" toView:self.view];
    //        return;
    //    }
    
    WZOutFrame *outFrame = self.outDataArray[indexPath.row];
    
    self.wzout = outFrame.wzOut;
    
    outFrame.wzOut.outIsSelected = !outFrame.wzOut.outIsSelected;
    self.selectedFlag = outFrame.wzOut.outIsSelected;
    if (!outFrame.wzOut.outIsSelected) {
        
        [self.signBtn setEnabled:NO];
        [self.signOutBtn setEnabled:NO];
        
        
    } else {// 选中
        
        //        if ([self.signFlag isEqualToString:@"2"]) {
        //
        //            [self.signBtn setEnabled:YES];
        //            [self.signOutBtn setEnabled:NO];
        //        }
        
        // 新的外出单
        if (!self.wzout.signBeginTime && !self.wzout.signEndTime) {
            
            [self.signBtn setEnabled:YES];
            [self.signOutBtn setEnabled:NO];
        }
        
        // 已签到而没有签退的
        if (self.wzout.signBeginTime && !self.wzout.signEndTime) {
            
            [self.signBtn setEnabled:NO];
            [self.signOutBtn setEnabled:YES];
        }
        
        // 已经签到并且签退的外出单
        if (self.wzout.signBeginTime && self.wzout.signEndTime) {
            
            
            NSString *beginTime = self.wzout.signBeginTime;
            NSString *endTime = self.wzout.signEndTime;
            
            NSInteger result = [NSDate compareWithDate:beginTime otherDate:endTime];
            // result == 0 same
            // result == 1 ascending
            // result == -1 descending
            
            if (result == 1) {
                
                [self.signBtn setEnabled:NO];
                [self.signOutBtn setEnabled:YES];
                
            } else if (result == -1) {
                
                [self.signBtn setEnabled:YES];
                [self.signOutBtn setEnabled:NO];
                
            } else {
                
                [self.signBtn setEnabled:YES];
                [self.signOutBtn setEnabled:NO];
                WZLog(@"时间比较结果为0, 签到签退两个时间相同");
            }
            
            /*
             if ([self.signFlag isEqualToString:@"2"]) {
             
             //
             WZLog(@"签退完毕");
             //                [self.signBtn setEnabled:YES];
             //                [self.signOutBtn setEnabled:NO];
             
             } else if ([self.signFlag isEqualToString:@"1"]) {
             
             WZLog(@"签到完, 但是为签退");
             
             //                [self.signBtn setEnabled:NO];
             //                [self.signOutBtn setEnabled:YES];
             
             } else if (!self.signFlag) { // 刚刚发完网络请求, signFlag == nil
             
             NSString *beginTime = self.wzout.signBeginTime;
             NSString *endTime = self.wzout.signEndTime;
             
             NSInteger result = [NSDate compareWithDate:beginTime otherDate:endTime];
             // result == 0 same
             // result == 1 ascending
             // result == -1 descending
             
             if (result == 1) {
             
             [self.signBtn setEnabled:NO];
             [self.signOutBtn setEnabled:YES];
             
             } else if (result == -1) {
             
             [self.signBtn setEnabled:YES];
             [self.signOutBtn setEnabled:NO];
             
             } else {
             
             WZLog(@"时间比较结果为0, 签到签退两个时间相同");
             }
             }
             
             */
            
        } //else if (self.wzout.signBeginTime && self.wzout.signEndTime && [self.signFlag isEqualToString:@"1"]) {
        
        //            WZLog(@"hhehheh");
        //        }
        
        
    }
    
    //    */
    
    [self.outDataArray enumerateObjectsUsingBlock:^(WZOutFrame *obj, NSUInteger idx, BOOL *stop) {
        if (![obj.wzOut.outId isEqualToString:self.wzout.outId]) {
            obj.wzOut.outIsSelected = NO;
        }
    }];
    
    [tableView reloadData];
}



#pragma mark - 定位弹框

- (void)setupAlertView {
    
    if (!IsIOS8) {
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"开启定位" message:OutManger_Location_Service_Message delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alert show];
        
    } else {
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"开启定位" message:OutManger_Location_Service_Message preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
            
        }];
        UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            
        }];
        [alert addAction:cancel];
        [alert addAction:confirm];
        [self presentViewController:alert animated:YES completion:nil];
    }
}


#pragma mark - alertView Delegate

- (void)alertViewCancel:(UIAlertView *)alertView {
    
    
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    
}


#pragma mark - 初始化子控件

- (void)addChildControl {
    
    //创建底部的签名控件
    UIView *signView = [[UIView alloc] init];
    signView.backgroundColor = WhiteColor;
    [self.view addSubview:signView];
    
    
    //划线
    UIView *line = [[UIView alloc] init];
    line.frame = CGRectMake(0, 0, self.view.width, 0.5f);
    line.backgroundColor = RGBCOLORWITH16COLOR(0xe5e5e5);
    [signView addSubview:line];
    
    
    //创建定位按钮
    UIButton *locationBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    locationBtn.frame = CGRectMake(HARDWARE_SCREEN_WIDTH - OppositeWidthRate(15) - 40.0f, CGRectGetMaxY(line.frame), 40.0f, 40.0f);
    [locationBtn setImage:[UIImage imageNamed:@"outLocation"] forState:UIControlStateNormal];
    [locationBtn addTarget:self action:@selector(showLocation) forControlEvents:UIControlEventTouchUpInside];
    [signView addSubview:locationBtn];
    
    //创建位置text
    UITextField *addressText = [[UITextField alloc] init];
    addressText.frame = CGRectMake(OppositeWidthRate(15),  CGRectGetMaxY(line.frame) + OppositeHeightRate(8), locationBtn.x - OppositeWidthRate(15), 24.0f);
    addressText.borderStyle = UITextBorderStyleNone;
    addressText.layer.borderColor = RGBCOLORWITH16COLOR(0xe5e5e5).CGColor;
    addressText.layer.borderWidth = 0.5f;
    addressText.textColor = RGBCOLORWITH16COLOR(0x333333);
    addressText.font = Font12;
    //    addressText.text = @"当前位置：北京市朝阳区建国路甲2号";
    addressText.textAlignment = UITextAlignmentLeft;
    addressText.leftViewMode = UITextFieldViewModeAlways;
    addressText.userInteractionEnabled = NO;
    
    UIView *leftView2 = [[UIView alloc] init];
    leftView2.frame = CGRectMake(0, 0, 15.0f, 15.0f);
    leftView2.backgroundColor = ClearColor;
    addressText.leftView = leftView2;
    [signView addSubview:addressText];
    self.addressText = addressText;
    
    //划线
    UIView *line1 = [[UIView alloc] init];
    line1.frame = CGRectMake(0, CGRectGetMaxY(locationBtn.frame) + 0.5f, self.view.width, 0.5f);
    line1.backgroundColor = RGBCOLORWITH16COLOR(0xe5e5e5);
    [signView addSubview:line1];
    
    
    //外出签到按钮
    UIButton *signBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [signBtn setBackgroundImage:[UIImage imageNamed:@"outSignNormal"] forState:UIControlStateNormal];
    [signBtn setBackgroundImage:[UIImage imageNamed:@"outSignHighlighted"] forState:UIControlStateHighlighted];
    [signBtn setBackgroundImage:[UIImage imageNamed:@"outSignDisabled"] forState:UIControlStateDisabled];
    signBtn.tag = 20001;
    signBtn.frame = CGRectMake(OppositeWidthRate(15), CGRectGetMaxY(line1.frame) + OppositeHeightRate(8), 140.0f, 34.0f);
    [signBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    signBtn.enabled = NO;
    [signView addSubview:signBtn];
    self.signBtn = signBtn;
    
    //外出签退
    UIButton *signOutBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [signOutBtn setBackgroundImage:[UIImage imageNamed:@"outSignOutNormal"] forState:UIControlStateNormal];
    [signOutBtn setBackgroundImage:[UIImage imageNamed:@"outSignOutHighligted"] forState:UIControlStateHighlighted];
    [signOutBtn setBackgroundImage:[UIImage imageNamed:@"outSignOutDisabled"] forState:UIControlStateDisabled];
    signOutBtn.tag = 20002;
    signOutBtn.frame = CGRectMake(self.view.width - 140.0f - OppositeWidthRate(15), CGRectGetMaxY(line1.frame) + OppositeHeightRate(8), 140.0f, 34.0f);
    [signOutBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    signOutBtn.enabled = NO;
    [signView addSubview:signOutBtn];
    self.signOutBtn = signOutBtn;
    
    
    //底部的签名控件frame
    signView.frame = CGRectMake(0, HARDWARE_SCREEN_HEIGHT - 64 - CGRectGetMaxY(signOutBtn.frame) - OppositeHeightRate(8), self.view.width, CGRectGetMaxY(signOutBtn.frame) + OppositeHeightRate(8));
    
    //创建数据空间tableView
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, signView.y) style:UITableViewStyleGrouped];
    tableView.showsVerticalScrollIndicator = NO;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.backgroundColor = ClearColor;
    tableView.delegate = self;
    tableView.dataSource = self;
    [self.view addSubview:tableView];
    self.tableView = tableView;
    
}

#pragma mark - 经纬度转化为CLLocation
- (CLLocationCoordinate2D)transformCoordinate2DWithPositionStr:(NSString *)positionStr{
    
    NSArray *postionArray = [positionStr componentsSeparatedByString:@","];
    CLLocationDegrees listLongitude = (CLLocationDegrees)[postionArray.firstObject doubleValue];
    CLLocationDegrees listLatitude = (CLLocationDegrees)[postionArray.lastObject doubleValue];
    
    CLLocationCoordinate2D coordiNate2D = CLLocationCoordinate2DMake(listLatitude, listLongitude);
    return coordiNate2D;
}


#pragma mark 懒加载
- (NSMutableArray *)outDataArray
{
    if (_outDataArray == nil) {
        _outDataArray = [NSMutableArray array];
    }
    return _outDataArray;
}

- (NSMutableArray *)coordinateArray {
    
    if (_coordinateArray == nil) {
        _coordinateArray = [NSMutableArray array];
    }
    return _coordinateArray;
}

#pragma mark - 懒加载

- (NSMutableArray *)listArray
{
    if (_listArray == nil) {
        _listArray = [NSMutableArray array];
    }
    return _listArray;
}

- (NSMutableArray *)outSignArray
{
    if (_outSignArray == nil) {
        _outSignArray = [NSMutableArray array];
    }
    return _outSignArray;
}


- (void) updateUI {
    
    if ([self.signFlag isEqualToString:@"1"]) {
        self.wzout.signBeginTime = [NSDate getCurrentDateWithDateFormatterStr:@"YYYY-MM-dd HH:mm:ss"];
        [MBProgressHUD showSuccess:@"签到成功"];
        self.signBtn.enabled = NO;
        self.signOutBtn.enabled = YES;
        
    } else {
        
        self.wzout.signEndTime = [NSDate getCurrentDateWithDateFormatterStr:@"YYYY-MM-dd HH:mm:ss"];
        [MBProgressHUD showSuccess:@"签退成功"];
        self.signOutBtn.enabled = NO;
        self.signBtn.enabled = YES;
    }
}

/**GCD group*/
/*
 // GCD 限制执行顺序
 dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
 dispatch_async(queue, ^{
 
 dispatch_group_t group = dispatch_group_create();
 
 dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
 
 __block CLGeocoder *geocoder = [[CLGeocoder alloc]init];
 [geocoder geocodeAddressString:wzout.outAddress completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
 //                                geocoder = nil;
 WZLog(@"地理编码成功!");
 if (!error) {
 
 CLPlacemark *placeMark = placemarks.firstObject;
 self.outCoordiNate2D = placeMark.location.coordinate;
 WZLog(@"返回的地标信息:%f; %f", placeMark.location.coordinate.latitude, placeMark.location.coordinate.longitude);
 
 // 计算距离
 [self distanceWithOutCoordinate2D:self.outCoordiNate2D userCoordinate:self.userCoordiNate2D];
 
 wzout.distance = self.distance;
 
 //                            for (CLPlacemark *placemark in placemarks) {
 //
 //                                self.outCoordiNate2D = placemark.location.coordinate;
 //                                WZLog(@"返回的地标信息:%f; %f", placemark.location.coordinate.latitude, placemark.location.coordinate.longitude);
 //                            }
 }
 
 }];
 
 });
 
 dispatch_group_notify(group, dispatch_get_main_queue(), ^{
 
 [self.outDataArray addObject:outFrame];
 
 });
 
 
 });
 */

@end
